﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NetTao.Model;

namespace NetTao.Analyser
{
    public class AnalyseBookReader : AnalyseBase
    {
        private IList<ChapterInfo> _bookReader;

        public IList<ChapterInfo> BookReader
        {
            get { return _bookReader ?? (_bookReader = new List<ChapterInfo>()); }
        }

        //private Dictionary<string, int> _dicBookReader;

        //public Dictionary<string, int> DicBookReader
        //{
        //    get { return _dicBookReader ?? (_dicBookReader = new Dictionary<string, int>()); }
        //}

        private int _bookReaderIndex;

        private int _chapterID;

        public int HasVipChapter { get; set; }

        public void AnalyseVolumeList()
        {
            //先将目录页的HTML切断成多个卷内容
            //1.qidian用正则分割,其他可以用find方法分割
            //2.发现卷后存入list,为后续chapter.volumeid
            _bookReaderIndex = 0;
            _chapterID = 1;
            HasVipChapter = 0;
            BookReader.Clear();
            var volumes = SplitVolumeHtml();
            IEnumerable<string> enumerable = volumes as string[] ?? volumes.ToArray();
            if (enumerable.Count() == 1)
            {
                var chapter = new ChapterInfo { articleid = Article.articleid, articlename = Article.articlename, chapterid = _chapterID };
                _chapterID++;
                chapter.chaptername = Config.ContentManage.Instace().Content.DefaultVolumeName;
                chapter.chapterorder = _bookReaderIndex;
                chapter.chaptertype = 1;
                BookReader.Add(chapter);
                _bookReaderIndex++;

                AnalyseChapterList(enumerable.First(), BookReader[_bookReaderIndex - 1]);
            }
            else
            {
                foreach (string volume in enumerable)
                {
                    if (AnalyseVolume(volume))
                    {
                        AnalyseChapterList(volume, BookReader[_bookReaderIndex - 1]);
                    }
                }
            }
        }

        private IEnumerable<string> SplitVolumeHtml()
        {
            var posBegin = 0;
            int pos;
            IList<string> volumes = new List<string>();
            if (Rule.PubVolumeSplit.Method.Equals("Match"))
            {
                var matchs = Regex.Matches(Content, Rule.PubVolumeSplit.Pattern, Rule.PubVolumeSplit.Options);
                for (int i = 0; i < matchs.Count; i++)
                {
                    Match match = matchs[i];
                    pos = Content.IndexOf(match.Groups[1].Value, posBegin, StringComparison.Ordinal);
                    if (pos < 0) break;

                    //将去掉的标记加上，用以正则查询volumeName
                    volumes.Add(Rule.PubVolumeSplit.FilterPattern + Content.Substring(posBegin, pos - posBegin));
                    posBegin = pos;
                }
                volumes.Add(Rule.PubVolumeSplit.FilterPattern + Content.Substring(posBegin, Content.Length - posBegin));
            }
            else
            {
                while (posBegin < Content.Length)
                {
                    pos = Content.IndexOf(Rule.PubVolumeSplit.Pattern, posBegin, StringComparison.Ordinal);
                    if (pos < 0) break;
                 
                    volumes.Add(Content.Substring(posBegin, Content.Length - pos - posBegin));
                    posBegin = pos;
                }
                volumes.Add(Content.Substring(posBegin, Content.Length - posBegin));
            }
            return volumes;
        }

        private bool AnalyseVolume(string volumeString)
        {
            Match match = Regex.Match(volumeString, Rule.PubVolumeName.Pattern, Rule.PubVolumeSplit.Options);
            if (match.Groups.Count == 0 || string.IsNullOrEmpty(match.Groups[1].Value))
                return false;

            var chapter = new ChapterInfo
                              {
                                  articleid = Article.articleid,
                                  articlename = Article.articlename,
                                  chapterid = _chapterID,
                                  lastupdate = int.Parse(DateTime.Now.ToString("yyMMddHHmm")),
                                  postdate = int.Parse(DateTime.Now.ToString("yyMMddHHmm"))
                              };
            _chapterID++;
            chapter.chaptername = match.Groups[1].Value;
            chapter.chapterorder = _bookReaderIndex;
            chapter.chaptertype = 1;
            BookReader.Add(chapter);
            //if (DicBookReader.ContainsKey(chapter.chaptername))//已经用章节名字作为KEY添加过,章节名称重复
            //{
            //    throw new Exception("[10003]");
            //}
            //else
            //{
            //    DicBookReader[chapter.chaptername] = _bookReaderIndex;
            //}
            _bookReaderIndex++;
            return true;
        }

        private void AnalyseChapterList(string volumeString, ChapterInfo volume)
        {
            var posBegin = _bookReaderIndex;
            var nameMatchs = Regex.Matches(volumeString, Rule.PubChapterName.Pattern, Rule.PubChapterName.Options);
            for (int i = 0; i < nameMatchs.Count; i++)
            {
                Match match = nameMatchs[i];
                var chapter = new ChapterInfo
                                  {
                                      articleid = Article.articleid,
                                      articlename = Article.articlename,
                                      chapterid = _chapterID,
                                      lastupdate = int.Parse(DateTime.Now.ToString("yyMMddHHmm")),
                                      postdate = int.Parse(DateTime.Now.ToString("yyMMddHHmm"))
                                  };
                _chapterID++;
                chapter.chaptername = match.Groups[1].Value;
                if (!string.IsNullOrEmpty(Rule.PubChapterName.FilterPattern))
                {
                    chapter.chaptername = chapter.chaptername.Replace(Rule.PubChapterName.FilterPattern, string.Empty);
                }
                chapter.chapterorder = _bookReaderIndex;
                chapter.chaptertype = 0;
                chapter.isnew = 1;
                chapter.ctype = 0;
                chapter.volumeid = volume.chapterid;
                chapter.volumename = volume.chaptername;
                BookReader.Add(chapter);
                //if (DicBookReader.ContainsKey(chapter.chaptername))//已经用章节名字作为KEY添加过,章节名称重复
                //{
                //    throw new Exception("[10003]");
                //}
                //else
                //{
                //    DicBookReader[chapter.chaptername] = _bookReaderIndex;
                //}
                _bookReaderIndex++;
            }
            //analyse chapter link
            string vipFlag = Rule.GetSiteName.Pattern; //MatchSingleValue(Rule.GetSiteName);
            //string chapterUrl = Rule.PubContentUrl.Pattern;
            MatchCollection linkMatchs = Regex.Matches(volumeString, Rule.PubChapter_GetChapterKey.Pattern,
                                                       Rule.PubChapter_GetChapterKey.Options);
            for (int i = 0; i < linkMatchs.Count; i++)
            {
                Match linkMatch = linkMatchs[i];

                if (posBegin >= _bookReaderIndex)
                    throw new Exception("Link's collection not match name's collection");

                if (string.IsNullOrEmpty(BookReader[posBegin].chaptername))
                {
                    BookReader[posBegin].chaptername = Config.ContentManage.Instace().Content.DefaultChapterName;
                }
                BookReader[posBegin].contentslink = Rule.PubContentUrl.Pattern;
                BookReader[posBegin].contentslink = BookReader[posBegin].contentslink.Replace("{ChapterKey}",linkMatch.Groups[1].Value);
                if (BookReader[posBegin].contentslink.Contains("{NovelKey}"))
                {
                    BookReader[posBegin].contentslink = BookReader[posBegin].contentslink.Replace("{NovelKey}",Article.contentslink);
                }
                if(!string.IsNullOrEmpty(Rule.PubContentUrl.FilterPattern))
                {
                    string[] arr = Rule.PubContentUrl.FilterPattern.Split('♂');
                    BookReader[posBegin].contentslink = BookReader[posBegin].contentslink.Replace(arr[0],
                                                                                                  arr.Length > 1
                                                                                                      ? arr[1]
                                                                                                      : string.Empty);
                }
                BookReader[posBegin].isvip = BookReader[posBegin].contentslink.Contains(vipFlag) ? 1 : 0;
                if (BookReader[posBegin].isvip == 1) HasVipChapter++;
                posBegin++;
            }
        }
    }
}
